var express = require('express');
var router = express.Router();
var utils = require('../functions/utils');

router.post('/', function(req,res)
{
/*
	Input parameters 
	 *		sessionId
	 *		userName
	 *		aboutMe : optional

*/
	var sessionId = req.body.sessionId;	utils.checkParamValue('sessionId' , sessionId);

	var userName = req.body.userName;	utils.checkParamValue('userName' , userName);
	var aboutMe = req.body.aboutMe;	//utils.checkParamValue('aboutMe' , aboutMe);
	var colorTheme = req.body.colorTheme;
	if(!utils.isValidString(String(colorTheme)))
		colorTheme = 0;


	utils.callLog(req);

	utils.sessionTraceLog(req);

	// 금지어 체크
	utils.checkProhibitedWord(userName);
	utils.checkProhibitedWord(aboutMe);


	var async = require('async');
	async.waterfall([
		function(cb)
		{
			utils.getUserIdWithSessionId(sessionId , cb);
		}
		,function(userId , cb) {
			if(!userId)
			{
				var err = new Error('Invalid session ID : ' + sessionId);
				err.code = '522';
				throw err;
			}

			///////////////////////////본 루틴//////////////////////////////

			// update하니까 master
			global.master_db.connection.getConnection(function(err,connection)
			{
				if(err)
				{
					throw err;
				}


				var input_param = [userId, userName , aboutMe , colorTheme];

				var sql = 'call api_updateProfile(? ,? , ? , ? , @result); SELECT @result AS result';

				var query = connection.query(sql, input_param , function (err, rows) 
				{
					connection.release();
					if(err)
					{
						throw err;
					}

					var ret = { };	 // 기본값은 성공

					switch(rows[1][0].result)
					{
						case 201:
							ret.code=201;
							break;
						default:
							throw new Error();

					}

					res.json(ret);
					res.end();

				}); // call api_updateProfile

			}); // getConnection

			////////////////////////////////////////////////////////////////////////

		}
	]); //waterfall
	
});

module.exports = router;